
from util import ReadFile, WriteFile
from xyztools import extractXYZLine

import datetime

def TranslateFile(filenameIn, filenameOut, translation):
    datestr = datetime.datetime.now().strftime("%d-%B-%Y")
    # Find the amount of translation we need to do!
    data = ReadFile(filenameIn)
    dataLines = [l for l in data.split("\n") if l.strip() and not l.strip().startswith("#") ]
    CommentLines = [l for l in data.split("\n") if l.strip() and l.strip().startswith("#") ]
    # copies comment lines and adds comment line showing the processing that's been done plus date.
    #outData = CommentLines + ["# Translated by (%d,%d,%d) using nrnTranslate.py"%translation] + ["# On: %s"%datestr]
    outData = CommentLines + ["# Translated by (%d,%d,%d) using nrnTranslate.py"%translation + " On: %s"%datestr]
    #outData = outData + ["# On: %s"%datestr] 
	
    #print translation
    
    for l in dataLines:
        i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)

        #Fixed traslate. Previously it was incorrectly translating x y and z by x value
        x = x + translation[0]
        y = y + translation[1]
        z = z + translation[2]
        
        X = X + translation[0]
        Y = Y + translation[1]
        Z = Z + translation[2]
        
        outData.append( "\t".join( [str(g) for g in [i,t,x,y,z,X,Y,Z,p] ] ) )
    WriteFile( filenameOut, "\n".join( outData) )
    




def nrnTranslate( nsFilenameSrc, nrnFilenameSrc,nsFilenameSink, nrnFilenameSink):
    print " -- Finding Translation"
    nsData = ReadFile(nsFilenameSrc)
    
    # Find the amount of translation we need to do!
    dataLines = [l for l in nsData.split("\n") if l.strip() and not l.strip().startswith("#") ]

    tPoint = None
    for l in dataLines:
        i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)

        if p==-1 and t==9:
            assert not tPoint
            tPoint = (-1.0*x,-1.0*y,-1.0*z)
            
    assert tPoint
    
    print " -- Translating by", tPoint  
    TranslateFile(nsFilenameSrc, nsFilenameSink, tPoint)
    TranslateFile(nrnFilenameSrc, nrnFilenameSink, tPoint)
    
    
    
    


    
